/*
 *  Copyright (C) 2021 Huawei Device Co., Ltd.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.rxohosnetworking;

import ohos.eventhandler.EventRunner;
import rx.Scheduler;
import rx.annotations.Experimental;

import java.util.concurrent.atomic.AtomicReference;

public class HosSchedulers {
    private static final AtomicReference<HosSchedulers> INSTANCE = new AtomicReference<>();

    private final Scheduler mainThreadScheduler;

    private static HosSchedulers getInstance() {
        for (; ; ) {
            HosSchedulers current = INSTANCE.get();
            if (current != null) {
                return current;
            }
            current = new HosSchedulers();
            if (INSTANCE.compareAndSet(null, current)) {
                return current;
            }
        }
    }

    private HosSchedulers() {
        RxHosSchedulersHook hook = RxHosPlugins.getInstance().getSchedulersHook();

        Scheduler main = hook.getMainThreadScheduler();
        if (main != null) {
            mainThreadScheduler = main;
        } else {
            mainThreadScheduler = new LooperScheduler(EventRunner.getMainEventRunner());
        }
    }

    /**
     * A {@link Scheduler} which executes actions on the Android UI thread.
     *
     * @return Scheduler
     */
    public static Scheduler mainThread() {
        return getInstance().mainThreadScheduler;
    }

    /**
     * A {@link Scheduler} which executes actions on {@code looper}.
     *
     * @param eventRunner 事件处理
     * @return Scheduler
     */
    public static Scheduler from(EventRunner eventRunner) {
        if (eventRunner == null) throw new NullPointerException("looper == null");
        return new LooperScheduler(eventRunner);
    }

    /**
     * Resets the current {@link } instance.
     * This will re-init the cached schedulers on the next usage,
     * which can be useful in testing.
     */
    @Experimental
    public static void reset() {
        INSTANCE.set(null);
    }
}
